package com.be.beadmin.device.controller;

import cn.hutool.core.date.DateUtil;
import com.be.beadmin.common.entity.PageEntity;
import com.be.beadmin.common.exception.BeadminException;
import com.be.beadmin.device.dto.output.EhsFileEx;
import com.be.beadmin.device.entity.EhsFile;
import com.be.beadmin.device.repository.EhsFileRepository;
import com.be.beadmin.project.Util.MinioUtil;
import com.be.beadmin.project.config.MinioConfig;
import com.be.beadmin.project.entity.FileInfo;
import com.be.beadmin.service.impl.MinioService;
import com.google.common.io.ByteStreams;
import io.minio.MinioClient;
import io.minio.errors.InvalidEndpointException;
import io.minio.errors.InvalidPortException;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.data.domain.Page;
import com.be.beadmin.device.service.EhsFileService;
import com.be.beadmin.device.dto.input.EhsFileDto;
import com.be.beadmin.common.utils.ResultModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.alibaba.excel.EasyExcel;
import org.springframework.web.multipart.MultipartFile;

/**
* @author zty
* @date 2023-08-13
**/
@RestController
public class EhsFileController {

    @Autowired
    private  EhsFileService ehsFileService;

    @Autowired
    private EhsFileRepository ehsFileRepository;

    @Autowired
    private MinioService minioService;

    MinioUtil minioUtil = new MinioUtil();

    private String bucketName = "ehsfile";


    @PostMapping(value = "/device/getEhsFileByPage")
    public ResultModel getEhsFileByPage(@RequestBody PageEntity pageEntity)  {
        return ResultModel.success(ehsFileService.getEhsFileByPage(pageEntity)) ;
    }

    @PostMapping("/device/addEhsFile")
    public ResultModel addEhsFile(@RequestBody EhsFileDto ehsFileDto){
        ehsFileService.addEhsFile(ehsFileDto);
        return ResultModel.success(ResultModel.ADD);
    }

    @PostMapping("/device/delEhsFile")
    public ResultModel delEhsFile(@RequestBody EhsFileDto ehsFileDto){
        ehsFileService.delEhsFile(ehsFileDto.getId());
        return ResultModel.success(ResultModel.DELETE);
    }


    @PostMapping("/device/updateEhsFile")
    public ResultModel updateEhsFile(@RequestBody EhsFileDto ehsFileDto){
        ehsFileService.updateEhsFile(ehsFileDto);
        return ResultModel.success(ResultModel.UPDATE);
    }


    @PostMapping("/device/exportEhsFile")
    public void exportEhsFile(HttpServletResponse response ,@RequestBody PageEntity pageEntity) throws IOException {
        Page<EhsFileEx> ehsFilePage = ehsFileService.getEhsFileByPage(pageEntity);
        List<EhsFileEx> ehsFileExes = ehsFilePage.getContent();
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("EhsFile接口", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), EhsFileEx.class).sheet("sheet1").doWrite(ehsFileExes);
    }

    @ApiOperation("判断bucket是否存在")
    @PostMapping ("/device/bucketExist")
    public ResultModel bucketExist(@ApiParam(value = "bucketName")@RequestParam String bucketName) throws InvalidPortException, InvalidEndpointException {
        boolean exists = minioUtil.bucketExists(bucketName);
        return ResultModel.success(exists);
    }

    @ApiOperation("新增附件信息")
    @PostMapping("/device/uploadEhsFile")
    public ResultModel uploadEhsFile(
                                      @ApiParam(value = "附件",required = true) @RequestParam("file") MultipartFile[] multipartFiles,
                                      @ApiParam(value = "ehsItem_id",required = true) @RequestParam String ehsitemId,
                                      @ApiParam(value = "文件名称") @RequestParam String fileName,
                                      @ApiParam(value = "备注") @RequestParam(required = false) String memo)  {
        try {
            ehsFileService.uploadEhsFile(ehsitemId, multipartFiles, fileName, memo, bucketName);
            return ResultModel.success(ResultModel.ADD);
        } catch (BeadminException e) {
            return ResultModel.error(-1,e.getMessage());
        } catch (Exception e) {
            return ResultModel.error(-2,e.getMessage());
        }

    }

    @ApiOperation("附件下载")
    @GetMapping("/device/downloadFile")
    public ResultModel downloadFile(@ApiParam(value = "附件id")@RequestParam String id,
                                    HttpServletResponse response) throws Exception {
        try {

            EhsFile ehsFile = ehsFileRepository.findEhsFileByIdAndDelete(id, 0);
            //System.out.println(ehsFile.getBucketName());
            //System.out.println(ehsFile.getFileName());
            String fileName = ehsFile.getFileName();
            String bucketName = ehsFile.getBucketName();
            String version =ehsFile.getVersion();
            String fileCode = ehsFile.getFileCode();
            String downloadFileName= fileCode+"+"+String.valueOf(version)+"+"+fileName;
            InputStream inputStream = minioService.downloadOne(bucketName, downloadFileName);
            response.addHeader("Accept-Ranges", "bytes");
            response.addHeader("Content-Disposition", "attachment;filename="+downloadFileName);
            response.addHeader("Content-Type", "text/plain;charset=utf-8");
            response.addHeader("Pragma","No-cache");
            response.addHeader("Cache-Control","No-cache");
            ServletOutputStream os = response.getOutputStream();

            ByteStreams.copy(inputStream, os);
            os.flush();
            return  ResultModel.success("下载成功");
        } catch (Exception e) {
            return ResultModel.error(99,"文件读取异常");
        }
    }
    @ApiOperation("附件下载2")
    @PostMapping("/device/downloadFile2")
    public ResultModel downloadFile2(@ApiParam(value = "附件id")@RequestParam String id,
                                     HttpServletResponse response) throws Exception {
        ehsFileService.downloadEhsFile(id,response);
        return null;

    }

    @ApiOperation("附件预览")
    @PostMapping("/device/previewFile")
    public ResultModel getFilePreviewUrl(@ApiParam(value = "附件id",required = true) @RequestParam String id)throws Exception{
        return ResultModel.success(ehsFileService.previewEhsFile(id));
    }


    @ApiOperation("创建bucket")
    @GetMapping("/device/createBucket")
    public ResultModel createBucket(@ApiParam(value = "bucketName")@RequestParam String bucketName) throws Exception {
        minioUtil.createBucketName(bucketName);
        return ResultModel.success("创建成功");
    }

//    @ApiOperation("预览")
//    @GetMapping("/device/previewFile")
//    public ResultModel previewFile(@RequestParam("file") String filePath, @RequestParam("type") String fileType) throws IOException{
//        return ResultModel.success(ehsFileService.previewFile(filePath, fileType));
//    }
}